package com.yrd.fssync.core;

import java.io.IOException;
import java.net.SocketException;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.jsoup.helper.DataUtil;

public class SyncEngine {
	Context context;
	String id;
	ISyncer syncer;
	ExecutorService singleThreadExecutor;  
	KeyList keyList;
	
	public SyncEngine(Context context,String id,ISyncer syncer) {
		this.context = context;
		this.id = id;
		this.syncer = syncer;
		this.singleThreadExecutor = Executors.newSingleThreadExecutor();
		keyList = new KeyList();
	}
	
	
	public String getId() {
		return id;
	}


	public void start() throws SocketException, IOException{
		syncer.open();
		Utils.printfln("同步引擎启动",syncer);
	}
	
	public void stop(){
		singleThreadExecutor.shutdown();
		syncer.close();
		Utils.printfln("同步引擎关闭",syncer);
	}
	
	public void post(SyncRequest request){
		keyList.add(request);
		singleThreadExecutor.execute(new Runnable() {
			@SuppressWarnings("unchecked")
			public void run() {
				while(!keyList.isEmpty()){
					try {
						SyncRequest request = keyList.poll();
						syncer.dispose(request);
						context.getTray().statusUping(request.titleString());
						;
						context.getHttpEngine().sendMessage(
								StringUtils.join("[",DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"),
								"] [",id,"] ",request.titleString()," (剩余：",keyList.size(),")"));
					} catch (Exception e) {
						e.printStackTrace();
						context.getTray().info("文件同步器", e.getLocalizedMessage());
						context.getTray().statusError();
						System.exit(1);
					}
					if(keyList.isEmpty()){
						context.getTray().statusNormal();
						context.getHttpEngine().sendMessage(
								StringUtils.join("[",DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"),
								"] [",id,"] 任务完成"));
					}
				}
			}
		});
	}
	
	
}
